<?php
class ImgAction extends CommonAction {
	
	function index(){
		if(!session(C('ADMIN_AUTH_KEY'))){
			$this->listmap = "site_id=".$this->siteid." and is_system=0";
		}else{
			$this->listmap = "1";
		}
		$this->listorder='id desc';
		//分类列表
		$catedb = M('Imgcate');
		$this-> cateList = $catedb -> where(array('site_id' => $this->siteid)) -> select();
		if($this->_get('cateid')){
			$this->listmap .= " and cate_id=".$this->_get('cateid');
			$this -> cateid = $this->_get('cateid');
		}
        parent::_list();
		$this->display();
	}
	function upload(){
		//设置缩略图最大宽度
        $this->thumbMaxWidth = 300;
        //设置缩略图最大高度
        $this->thumbMaxHeight = 300;
		parent::upload();
	}
	public function add(){
		$this->pid = $this->_get('pid');
		if(!session(C('ADMIN_AUTH_KEY'))){
		    $this->imgcate_id = M('Imgcate')->where(array('site_id' => $this->siteid))->select();
		}else{
			$this->imgcate_id = M('Imgcate')->where("site_id=".$this->siteid." or is_system = 1")->select();
		}
		parent::add();
	}
	//
	public function delete(){
		if($this->_get('id')){
			$id = $this->_get('id');
			$map['id'] = array('in', $id);
			$data = $this->dao->where($map)->select();
			foreach($data as $v){
				if(session(C('ADMIN_AUTH_KEY'))){
					$this->delImgBypath($v['img_url']);
				}else{
					if($v['site_id'] == $this->siteid){
						$this->delImgBypath($v['img_url']);
					}
					
				}
					
			}
			parent::delete();
		}
	}
	//写入数据库
	public function insert(){
		if($this->_post('img_list')){
			$data['cate_id'] = $this->_post('imgcate_id')? intval($this->_post('imgcate_id')):0;
			$imgcateDB = M('Imgcate');
			$cate = $imgcateDB ->where(array('id' => $data['cate_id'])) -> find();
			if($cate['is_system'] ==1){
				$data['is_system'] = 1;
			}
			$re = $this->dao->where("img_url in(".$this->_post('img_list').") and site_id=".$this->siteid)->data($data)->save();
			
			//echo $this->dao->getLastSql();
			if($re !== false){
				exit('OK');
			}
		}
	}
	//图片选择框
	public function imagesBox(){
		$this->listorder = "is_system, id desc";
		$imgcateDB = M('Imgcate');
		$this->listmap="(user_id =".session(C('USER_AUTH_KEY') )." or is_system=1)";
		if($this->_get('cate_id')){
			$this->listmap .= " and (cate_id=".$this->_get('cate_id').")";
		}
		$this->cate_id = $imgcateDB -> where("site_id=".$this->siteid." or is_system=1") ->select();
		parent::_list();
		$this->assign('curcate',$this->_get('cate_id'));
		//echo $this->dao->getLastSql();
		
		
		if(isMobile()){
			$this->display('Public:imagesBoxMobile');exit;
		}
		
		
		$this->display('Public:imagesBox');
	}
	
	//移动分类
	public function move(){
		if($this->_get('category_id')){
			$category_id=$this->_get('category_id');
			$ids=$this->_get('id');
			$map['id'] = array('in', $ids);
			$data['cate_id']=$category_id;
			$re = $this->dao->where($map)->data($data)->save();
			if($re !== false){
			    $this->success('成功移动',U('index'));
			}else{
				$this->error($this->dao->getError());
			}
		}else{
			$this->error('参数错误，没有选择分类！');
		}
	}
	
	
	
	
	
	public function upload_Img()
    {

        if ($this->_post('imgo')) {
            $imgo_url2 = $this->_post('imgo_url');
            $imgo_url = $_SERVER['DOCUMENT_ROOT'] . $imgo_url2;
            header('Content-type: image/jpeg');
            $source = imagecreatefromjpeg($imgo_url);
            if ($this->_post('imgo') == 'left') {
                $jd = 90;
            }
            if ($this->_post('imgo') == 'right') {
                $jd = -90;
            }

            $rotate = imagerotate($source, $jd, 0);
            ImageJpeg($rotate, $imgo_url);
            echo json_encode($imgo_url2);

            exit;
        }
 

        $png = $this->_post('png');
        $this->assign('id', $this->_get('id'));
        if (!isset($png)) {
            $this->display('Public:upload_ImgMobile');
            exit();
        } else {


            $path2 = '/Public/Uploads/'.$this->siteid.'/mobile/'.date('Y-m-d') .'/'. time() . '.jpg';
            $path = $_SERVER['DOCUMENT_ROOT'] . $path2;
            if (!is_dir(pathinfo($path, PATHINFO_DIRNAME) . '/')) {
                mkdir(pathinfo($path, PATHINFO_DIRNAME) . '/', 511, true);
            }
            $this->base64_to_png("" . str_replace('data:image/jpeg;base64,', '', $png), $path);
            $url['img_url'] = $path2;
			$imgdata['img_url'] = str_replace('/Public/', '/', $path2);
			$imgdata['site_id'] = $this->siteid;
			$imgdata['size'] = filesize($path);
			$imgdata['user_id'] = session(C('USER_AUTH_KEY') );
			$imgdata['cate_id'] = 0;
			M('Img')->data($imgdata)->add();
			
			
            echo "<script>window.parent.uploaded('{$path2}','" . $this->_get('id') . "');</script>";
            $this->display('Public:upload_ImgMobile');
        }


    }

    function base64_to_png($inputfile, $outputfile)
    {
        $imageData = $inputfile;
        $file = fopen($outputfile, "w");
        fwrite($file, base64_decode($imageData));
        fclose($file);
    }
	
	//剪切头像
	public function Jcrop(){
 	if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {  
 	$id=$this->memberInfo['id'];
	//$src=$this->db->where("member_id= $id")->getField('img_url');	
	
	$src='.'.$_POST['img_url'] = $_POST['src']; 
	$bigsrc = pathinfo($src, PATHINFO_DIRNAME).'/thumb_'.pathinfo($src, PATHINFO_FILENAME).'.'.pathinfo($src, PATHINFO_EXTENSION);
	
	$images=getimagesize($src);
	
 	//$targ_w = $targ_h=540;
	$targ_w=$this->_post('w');
	$targ_h=$this->_post('h');
	 
	$jpeg_quality=100;
 	$img_r = imagecreatefromjpeg($src);
	//保存原图
	
	imagejpeg($img_r,$bigsrc,$jpeg_quality);
	
	
	
	$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
    imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
	$targ_w,$targ_h,$_POST['w'],$_POST['h']);
 	imagejpeg($dst_r,$src,$jpeg_quality);
	//$url=U('Member/Vcard/edit');
 	echo 'OK';
	exit;
	 
  
    }
 
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	public function upload_Img1()
	{
	
		if ($this->_post('imgo')) {
			$ret['img_url'] = $this->_post('imgo_url');
			$imgo_url2 = $this->_post('imgo_url');
			
			$imgo_url = $_SERVER['DOCUMENT_ROOT'] . $imgo_url2;
			header('Content-type: image/jpeg'); 
			$source = imagecreatefromjpeg($imgo_url);
			if ($this->_post('imgo') == 'left') {
				$jd = 90;
			}
			if ($this->_post('imgo') == 'right') {
				$jd = -90;
			}
			$rotate = imagerotate($source, $jd, 0);
			imagejpeg($rotate, $imgo_url); 
			echo json_encode($ret);
			exit;
		}
		$png = $this->_post('png');
		$path = 'static/uploads/' . date('Y-m-d') . '/' . time() . '.jpg';
		$path2 = './' . $path;
		if (!is_dir(pathinfo($path, PATHINFO_DIRNAME) . '/')) {
			mkdir(pathinfo($path, PATHINFO_DIRNAME) . '/', 511, true);
		}
		$this->base64_to_png1("" . str_replace('data:image/jpeg;base64,', '', $png), $path2);
		$url['img_url'] = '/'.$path;
		echo json_encode($url);
	}
	
	private function base64_to_png1($inputfile, $outputfile)
	{
		$imageData = $inputfile;
		$file = fopen($outputfile, "w");
		fwrite($file, base64_decode($imageData));
		fclose($file);
	}
	
	//剪切头像
	public function Jcrop1()
	{
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$src = '.' . $_POST['img_url'] = $_POST['src'];
			$bigsrc = pathinfo($src, PATHINFO_DIRNAME) . '/thumb_' . pathinfo($src, PATHINFO_FILENAME) . '.' . pathinfo($src, PATHINFO_EXTENSION);
	echo $src;
			$images = getimagesize($src);
	        //$targ_w = $targ_h=540;
			$targ_w = $this->_post('w');
			$targ_h = $this->_post('h');
	
			$jpeg_quality = 100;
			$img_r = imagecreatefromjpeg($src);
	        //保存原图
			imagejpeg($img_r, $bigsrc, $jpeg_quality);
			$dst_r = imagecreatetruecolor($targ_w, $targ_h);
			imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x'], $_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
			imagejpeg($dst_r, $src, $jpeg_quality);
			echo 'OK';
		}
	
	
	}
	
	
	
	
	
	
	
	
}
